package com.example.demo.mapper;

import com.example.demo.entity.Equconnect;
import org.apache.ibatis.annotations.*;
import com.example.demo.entity.Equipment;
import org.springframework.transaction.annotation.Transactional;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Param;
//import org.apache.ibatis.annotations.Provider;
import org.apache.ibatis.annotations.Options;
import java.util.List;
import java.util.Map;

@Mapper
public interface EquipmentMapper {

    @Select("select eid from equconnect where pjId = #{pjid}")
    public List<Integer> findEquIdOfProject(@Param("pjid") int pjid);

    @Select("select * from equipment where eid = #{eId}")
    public Equipment findEquById(@Param("eId") int eid);

    @Delete("delete from equconnect where eId = #{eid}")
    public int deleteEquOfProject(@Param("eid") int eid);

    /*@Transactional
    @Delete({
            "<script>",
            "delete from equconnect",
            "<where>",
            "<if test='eids != null and !eids.isEmpty()'>",
            "where eId IN",
            "<foreach item='eid' collection='eids' open='(' separator=',' close=')'>",
            "#{eid}",
            "</foreach>",
            "</if>",
            "</where>",
            "</script>"
    })
    int deleteEquListOfProject(@Param("eids") List<Integer> eids);*/



    @Transactional
    @DeleteProvider(type = SqlProvider.class, method = "deleteEquListOfProject")
    int deleteEquListOfProject(@Param("eIds") List<Integer> eIds);

    class SqlProvider {

        public String deleteEquListOfProject(Map<String, Object> params) {
            List<Integer> ids = (List<Integer>) params.get("eIds");
            StringBuilder sql = new StringBuilder();
            sql.append("DELETE FROM equconnect WHERE eId IN (");
            for (int i = 0; i < ids.size(); i++) {
                sql.append(ids.get(i));
                if (i < ids.size() - 1) {
                    sql.append(",");
                }
            }
            sql.append(")");
            return sql.toString();
        }
    }
    @Insert("INSERT INTO equipment (eName,eUnit) values (#{equipment.eName},#{equipment.eUnit})")
    @Options(useGeneratedKeys = true, keyProperty = "eId")
    public int addEquOfProject(@Param("equipment") Equipment equipment);

    @Insert("INSERT INTO equconnect (pjId, eId) values (#{equconnect.pjId}, #{equconnect.eId})")
    @Options(useGeneratedKeys = true, keyProperty = "cId")
    public int addEquConnect(@Param("equconnect") Equconnect equconnect);
}
